package cn.jhc.transport;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;

import cn.jhc.transport.fragment.EnvironmentFragment;
import cn.jhc.transport.view.SenseView;

public class MainActivity extends AppCompatActivity {

    private Timer timer;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == EnvType.CO2.ordinal()){
                Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                if(fragment != null){
                    SenseView senseView = (SenseView)fragment.getView().findViewById(R.id.sense_view);
                    if(senseView != null){
                        senseView.setCurrentValue(msg.arg1);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        EnvironmentFragment environmentFragment = new EnvironmentFragment();
        transaction.add(R.id.fragment_container, environmentFragment).commit();


        TimerTask task = new UpdateSenseTask(handler);
        timer = new Timer();
        timer.schedule(task, 0, 3000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
